package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.Admin;
import com.tanhua.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //登录
    public Map login(Map map) {
        //1、获取登录的请求参数 username ， password，verificationCode，uuid
        String username = map.get("username").toString();
        String password = map.get("password").toString();
        String verificationCode = map.get("verificationCode").toString();
        String uuid = map.get("uuid").toString();
        //2、比较验证码是否一致
        String value = redisTemplate.opsForValue().get(Constants.CAP_CODE + "_" + uuid);
        //3、如果不一致，抛出异常
        //明文 MD5
        System.out.println("password=" + password);
        password = SecureUtil.md5(password); //对输入的密码加密
        System.out.println("password=" + password);

        if(StringUtils.isEmpty(value) || !verificationCode.equalsIgnoreCase(value)) {
            throw new BusinessException("验证码错误");
        }
        //4、如果一致，删除验证码，根据用户名查询管理员
        redisTemplate.delete(Constants.CAP_CODE + "_" + uuid);
        QueryWrapper<Admin> qw = new QueryWrapper<Admin>();
        qw.eq("username",username);
        Admin admin = adminMapper.selectOne(qw);
        //5、判断对象是否存在，密码是否和输入的一致
        //6、不一致，抛出异常
        if(admin == null || !password.equals(admin.getPassword())) {
            throw new BusinessException("用户名或者密码错误");
        }
        //7、如果一致，生成token并构造返回
        Map params = new HashMap();
        params.put("id",admin.getId());
        params.put("username",admin.getUsername());
        String token = JwtUtils.getToken(params);
        //8、构造返回
        Map retMap  = new HashMap();
        retMap.put("token",token);
        return retMap;
    }

    //获取当前登录管理员的身份信息
    public AdminVo profile() {
        //1、获取当前管理员的ID
        Long id = AdminHolder.getUserId();
        //2、根据id查询管理员对象
        Admin admin = adminMapper.selectById(id);
        //3、构造vo
        return AdminVo.init(admin);
    }




}
